package ai.people.netmon.gateway.filter;

import ai.people.netmon.framework.constant.CloudConstant;
import ai.people.core.common.util.IpAddressUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关修改标题过滤器
 *
 * @author yuanqinglong
 * @date 2022/2/15 16:52
 */
@Component
public class ModifyHeaderFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String[] headerValues = {new String(Base64Utils.encode((CloudConstant.GATEWAY_TOKEN_VALUE).getBytes()))};
        // 增加网关转发请求头标识
        ServerHttpRequest build = exchange.getRequest().mutate()
                .header(CloudConstant.GATEWAY_TOKEN_HEADER, headerValues)
                .header(CloudConstant.GATEWAY_ORIGIN_IP_HEADER, IpAddressUtil.getIpAddress(exchange.getRequest()))
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(build).build();
        return chain.filter(newExchange);
    }
}
